package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"unicode/utf8"

	// brotli "github.com/google/brotli/go/cbrotli"
	"github.com/andybalholm/brotli"
)

//什么是br
// br 指的是 Brotli，是一种全新的数据格式，无损压缩，压缩比极高（比gzip高的）
// Brotli具体介绍：https://www.cnblogs.com/Leo_wl/p/9170390.html
// Brotli优势：https://www.cnblogs.com/upyun/p/7871959.html

const sendMsgUrl = "https://api.live.bilibili.com/msg/send"

var Cookie string
var SubMsgString bool

var sendMsgHeader = http.Header{
	"Host":            []string{"api.live.bilibili.com"},
	"Connection":      []string{"keep-alive"},
	"Accept":          []string{"*/*"},
	"User-Agent":      []string{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"},
	"Accept-Encoding": []string{"gzip, deflate, br"},
	"Accept-Language": []string{"zh-CN,zh;q=0.9"},
	"Origin":          []string{"https://live.bilibili.com"},
	"Referer":         []string{"https://live.bilibili.com/"},
	"Sec-Fetch-Site":  []string{"same-site"},
	"Sec-Fetch-Mode":  []string{"cors"},
	"Sec-Fetch-Dest":  []string{"empty"},
}

var client = &http.Client{}

//  SendMsg 2021-08-31 22:15:33
//  @Description:
//  @param msg string
//  @return err error
func SendMsg(msg string) (err error) {

	if msg == "" || Cookie == "" {
		return
	}

	if utf8.RuneCountInString(msg) > 20 {
		if !SubMsgString {
			return
		}

		r := []rune(msg)
		msg = string(r[:20])
	}

	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	_ = writer.WriteField("bubble", "0")
	_ = writer.WriteField("msg", msg)
	_ = writer.WriteField("color", "16777215")
	_ = writer.WriteField("mode", "1")
	_ = writer.WriteField("fontsize", "25")
	_ = writer.WriteField("rnd", "1630410317")
	_ = writer.WriteField("roomid", "8290796")
	_ = writer.WriteField("csrf", "c028f41ea8a10ad166ab2f499c636427")
	_ = writer.WriteField("csrf_token", "c028f41ea8a10ad166ab2f499c636427")

	err = writer.Close()
	if err != nil {
		return
	}

	fmt.Println(len(payload.String()))

	req, err := http.NewRequest(http.MethodPost, sendMsgUrl, payload)
	if err != nil {
		return err
	}

	req.Header = sendMsgHeader
	req.Header.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryg3Bo1agxAzAzMLPk")
	//req.Header.Add("Content-Length", strconv.Itoa(len(payload.String())))
	//req.Header.Add("Content-Length", "100")
	req.Header.Add("Cookie", Cookie)

	req.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(brotli.NewReader(res.Body))
	if err != nil {
		return err
	}

	type Resp struct {
		Code    int         `json:"code"`
		Data    interface{} `json:"data"`
		Message string      `json:"message"`
		Msg     string      `json:"msg"`
	}

	result := &Resp{}
	err = json.Unmarshal(body, result)
	if err != nil {
		return err
	}
	if result.Code != 0 {
		return errors.New(result.Message)
	}
	return nil
}
